<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2019/4/18
 * Time: 20:28
 */

namespace app\Module\Index\Controller;


use app\Module\Index\Logic\MessageLogic;
use app\Module\Index\Logic\MessageType;
use app\Module\Index\Model\CircleModel;
use app\Module\Index\Model\CircleTypeModel;
use app\Module\Index\Model\LogCircleShareModel;
use app\Module\Index\Model\UserModel;

class CircleController extends CheckAuth
{

    /**
     * 添加圈子
     *
     * @verify string|null $slideshows
     * @verify string      $type 类型
     * @verify string      $name
     * @verify string|null $desc
     * @verify string      $logo Logo
     * @return string
     */
    public function addAction($slideshows, $type, $name, $desc, $logo)
    {
        $slideshows = json_decode($slideshows, true);
        $type       = json_decode($type, true);

        $type_  = [];
        $oneIds = [];
        if (!empty($type)) {
            foreach ($type as $item) {
                if (empty($item['one']) || empty($item['two'])) {
                    return fail('类型错误');
                }
                $oneIds[] = $item['one'];
                foreach ($item['two'] as $two) {
                    $type_[] = [
                        'one_type_id' => $item['one'],
                        'two_type_id' => $two,
                    ];
                }
            }
        }

        $oneIdCount  = count($oneIds);
        $oneIdCount_ = count(array_unique($oneIds));
        if ($oneIdCount_ != $oneIdCount) {
            return fail('类型不能重复');
        }

        $circleModel = new CircleModel();
        // 检查名称是否重复
        $circleModel->addWhere(['name' => $name]);
        $circleModel->addWhere('user_id', $this->userId, '!=');
        $data = $circleModel->row();
        if (!empty($data)) {
            return fail('名称已存在，可向客服申述拿回名称');
        }

        // 查看是否加入圈子
        $data = $circleModel->row(['user_id' => $this->userId,]);
        if (!empty($data)) {
            return $this->update($slideshows, $type, $name, $desc, $logo);
        }

        $circleId = $circleModel->insert([
            'logo'      => $logo,
            'name'      => $name,
            'user_id'   => $this->userId,
            'desc'      => $desc,
            'created'   => now(),
            'updated'   => now(),
            'slideshow' => implode(',', $slideshows),
        ]);

        foreach ($type_ as $key => $item) {
            $item['circle_id'] = $circleId;
            $type_[$key]       = $item;
        }

        $circleTypeModel = new CircleTypeModel();
        $circleTypeModel->insert($type_);

        $userModel = new UserModel();
        $userModel->update([
            'circle_id' => $circleId,
        ], [
            'id' => $this->userId,
        ]);

        $messageLogic = new MessageLogic();
        $messageLogic->add($this->userId, $this->userId, $circleId, MessageType::SYSTEM, '欢迎您加入圈子，客服人员将会尽快为您审核！');

        return success($circleId);
    }

    /**
     * 更新圈子信息
     *
     * @verify array|null  $slideshows
     * @verify array       $type 类型
     * @verify string      $name
     * @verify string|null $desc
     * @verify string      $logo Logo
     * @return string
     */
    public function update($slideshows, $type, $name, $desc, $logo)
    {
        $type_  = [];
        $oneIds = [];
        if (!empty($type)) {
            foreach ($type as $item) {
                if (empty($item['one']) || empty($item['two'])) {
                    return fail('类型错误');
                }
                $oneIds[] = $item['one'];
                foreach ($item['two'] as $two) {
                    $type_[] = [
                        'one_type_id' => $item['one'],
                        'two_type_id' => $two,
                    ];
                }
            }
        }

        $oneIdCount  = count($oneIds);
        $oneIdCount_ = count(array_unique($oneIds));
        if ($oneIdCount_ != $oneIdCount) {
            return fail('类型不能重复');
        }

        $circleModel = new CircleModel();
        $circleData  = $circleModel->row(['user_id' => $this->userId,]);
        if (empty($circleData)) {
            return fail('未加入圈子');
        }

        $circleModel->update([
            'logo'      => $logo,
            'name'      => $name,
            'user_id'   => $this->userId,
            'desc'      => $desc,
            'slideshow' => implode(',', $slideshows),
            'audit'     => 'wait',
            'updated'   => now(),
        ], ['id' => $circleData['id']]);

        foreach ($type_ as $key => $item) {
            $item['circle_id'] = $circleData['id'];
            $type_[$key]       = $item;
        }

        $circleTypeModel = new CircleTypeModel();
        $circleTypeModel->delete(['circle_id' => $circleData['id']]);
        $circleTypeModel->insert($type_);

        $userModel = new UserModel();
        $userModel->update([
            'circle_id' => $circleData['id'],
        ], [
            'id' => $this->userId,
        ]);

        return success();
    }


    /**
     * 获取用户圈子信息
     * @verify int|null $id
     * @return string
     */
    public function getAction($id)
    {
        $circleModel = new CircleModel();
        if (empty($id)) {
            $circleModel->addWhere(['user_id' => $this->userId,]);
        } else {
            $circleModel->addWhere(['circle.id' => $id,]);
        }
        $circleModel->setFields([
            'circle.audit',
            'circle.id',
            'circle.logo',
            'circle.name',
            'circle.cause',
            'circle.desc',
            'circle.account_type',
            'circle.slideshow',
            'user.id as user_id',
            'user.username',
            'user.address_name',
            'user.address',
            'user.address',
            'user.latitude',
            'user.longitude',
            'user.mobile',
        ]);
        $circleModel->setJoin('user', 'user.circle_id = circle.id');
        $data = $circleModel->row([], 600);

        if (!empty($data)) {
            $circleTypeModel = new CircleTypeModel();
            $circleTypeModel->setJoin('circle_one_type', 'circle_one_type.id=circle_type.one_type_id');
            $circleTypeModel->setJoin('circle_two_type', 'circle_two_type.id=circle_type.two_type_id');
            $circleTypeModel->addWhere('circle_id', $data['id']);
            $circleTypeModel->setFields('circle_one_type.id as one_type_id,GROUP_CONCAT(DISTINCT circle_two_type.id) as two_type_id,circle_one_type.name as one_type_name,GROUP_CONCAT(DISTINCT circle_two_type.name) as two_type_name');
            $circleTypeModel->addGroup(['circle_id', 'circle_one_type.id']);
            $dataType     = $circleTypeModel->select([], 600);
            $data['type'] = $dataType;

            if ($this->userId == $data['user_id']) {
                $data['is_me'] = true;
            } else {
                $data['is_me'] = false;
            }
        }

        return success($data);
    }

    /**
     * 获取圈子列表
     *
     * @param     $one_type_id
     * @param     $two_type_id
     * @param int $page
     * @param int $limit
     * @return string
     */
    public function getListAction($one_type_id, $two_type_id, $page = 1, $limit = 20)
    {
        $circleModel = new CircleModel();
        $circleModel->setFields([
            'circle.id',
            'circle.logo',
            'circle.name',
            'circle.desc',
            'circle.account_type',
            'circle.slideshow',
            'user.id as user_id',
            'user.address_name',
            'user.address',
            'user.address',
            'user.latitude',
            'user.longitude',
            'user.mobile',
        ]);
        $circleModel->setPage($page, $limit);
        $circleModel->addWhere('audit', 'pass');
        if (!empty($one_type_id)) {
            $circleModel->setJoin('circle_type', 'circle_type.circle_id = circle.id');
            $circleModel->addWhere('circle_type.one_type_id', $one_type_id);
            if (!empty($two_type_id)) {
                $circleModel->addWhere('circle_type.two_type_id', $two_type_id);
            }
            $circleModel->addGroup(['circle_type.circle_id']);
        }

        $circleModel->addOrder('circle.created', false);
        $circleModel->setJoin('user', 'user.circle_id = circle.id');
        $data = $circleModel->select([], 600);
        $ids  = [];
        foreach ($data as $datum) {
            $ids[] = $datum['id'];
        }

        if (!empty($ids)) {
            $circleTypeModel = new CircleTypeModel();
            $circleTypeModel->setJoin('circle_one_type', 'circle_one_type.id=circle_type.one_type_id');
            $circleTypeModel->setJoin('circle_two_type', 'circle_two_type.id=circle_type.two_type_id');
            $circleTypeModel->addWhere('circle_id', $ids);
            $circleTypeModel->setFields('circle_id,circle_one_type.id as one_type_id,GROUP_CONCAT(DISTINCT circle_two_type.id) as two_type_id,circle_one_type.name as one_type_name,GROUP_CONCAT(DISTINCT circle_two_type.name) as two_type_name');
            $circleTypeModel->addGroup(['circle_id', 'circle_one_type.id']);
            $dataType = $circleTypeModel->select([], 600);
        } else {
            $dataType = [];
        }

        $dataType_ = [];
        foreach ($dataType as $item) {
            if (!isset($dataType_[$item['circle_id']])) {
                $dataType_[$item['circle_id']] = [];
            }
            $dataType_[$item['circle_id']][] = [
                'one_type_id'   => $item['one_type_id'],
                'two_type_id'   => $item['two_type_id'],
                'one_type_name' => $item['one_type_name'],
                'two_type_name' => $item['two_type_name'],
            ];
        }

        foreach ($data as $key => $datum) {
            if (isset($dataType_[$datum['id']])) {
                $datum['type'] = $dataType_[$datum['id']];
            } else {
                $datum['type'] = [];
            }
            $data[$key] = $datum;
        }

        return success($data);
    }

    /**
     * 根据类型获取圈子列表
     *
     * @verify int $type_id
     * @verify string|null $name
     * @verify int|null $page
     * @verify int|null $limit
     *
     * @return string
     */
    public function getListByTypeAction($type_id = -1, $name = '', $page = 1, $limit = 10)
    {
        $circleTypeModel = new CircleTypeModel();
        $circleTypeModel->setTableByname('ct_');
        $circleTypeModel->setFields('cir_.*,GROUP_CONCAT(DISTINCT ct_.one_type_id),GROUP_CONCAT(DISTINCT cot_.`name`) AS one_type_name,GROUP_CONCAT( DISTINCT ctt_.id ) AS two_type_id,GROUP_CONCAT( DISTINCT ctt_.name ) AS two_type_name ');
        $circleTypeModel->setJoin('circle_one_type AS cot_', 'ct_.one_type_id = cot_.id');
        $circleTypeModel->setJoin('circle_two_type AS ctt_', 'ct_.two_type_id = ctt_.id');
        $circleTypeModel->setJoin('circle AS cir_', 'cir_.id = ct_.circle_id ');
        if ($type_id == -1) {
        } else {
            $circleTypeModel->addWhere('ct_.one_type_id', $type_id);
        }

        if (!empty($name)) {
            $circleTypeModel->addLike('cir_.name', $name);
        }


        $circleTypeModel->addGroup('cir_.id ');
        $circleTypeModel->addOrder('cir_.score', false);
        $circleTypeModel->setPage($page, $limit);

        $data = $circleTypeModel->select();

        return success($data);
    }

    /**
     * 添加圈子分享量
     * @verify int $circle_id
     * @return string
     */
    public function addShareNumAction($circle_id)
    {
        $logCircleShareModel = new LogCircleShareModel();
        $logCircleShareModel->addWhere('created', date("Y-m-d", strtotime("-1 hour")), '>=');
        $logCircleShareModel->addWhere([
            'circle_id' => $circle_id,
            'user_id'   => $this->userId,
        ]);
        $shareNum = $logCircleShareModel->count('1', null, 600);
        // 每个用户每小时只能增加一个
        if ($shareNum > 0) {
            return success();
        }

        $logCircleShareModel->insert([
            'circle_id' => $circle_id,
            'user_id'   => session('userId'),
            'created'   => now(),
        ]);

        $circleModel = new CircleModel();
        $circleData  = $circleModel->row(['id' => $circle_id,]);

        $messageLogic = new MessageLogic();
        $messageLogic->add($this->userId, $circleData['user_id'], $circle_id, MessageType::CIRCLE_SHARE, '');

        $circleModel->update('share_num=share_num+1', ['id' => $circle_id]);
        return success();
    }
}
